function resetInsurancePaymentForm() {
    resetFormExt('patientDetailsInfo', true);
    $('#dobText').text('');
    $('#insuranceNumberTxt').text('');
    $('#insuranceUsageTxt').text('');
    $('#correctRouteChk').removeAttr('checked');
    $('#36MonthChk').removeAttr('checked');
    $('#insurancePaymentContentDiv').html('');
}

function collectMoney(print) {
    var ret = isReadyToSubmitInsurancePayment();
    if (!ret['result']) {
        showMessage('insurancePaymentMsg', ret['msg'], 'error');
        return;
    }
    clearText('insurancePaymentMsg');
    var amount = $.trim($('input#realAmount').val());
    var lcInt   =   locale(decimalPoint, thousandSep, 0);
    var val     =   parseLcNum(amount, lcInt);
    styledAmount = number_format(val, 0, ',', ' ');  
    var message  =  _('Are you sure to collect?') + 
        '<p>' + _('Amount: <span class="bigImpression">{0}</span>',styledAmount) + '</p>';   
    
    var buttons = {};
    buttons[_('Close')] = function() {
        $(this).dialog('close');        
    };    
    buttons[_('Ok')] = function() {
        $(this).dialog('close');
        submitCollecting(print)        
    };
    generalDialog(null, _('Collecting payment'),  message, null, {
        autoOpen: true,         
        bgiframe: true,
        resizable: false,
        modal: true,
        buttons: buttons
    }, _('Ok'));
}

function isReadyToSubmitInsurancePayment() {
    var ret =   new Array();
    ret['result']   =   true;
    ret['msg']      =   '';
    
    // Amount must not be empty
    var amount = $.trim($('input#realAmount').val());    
    if (amount.length == 0) {   
        ret['result']  =   false;
        ret['msg']     =   _("Please fill in amount.");
        $('input#realAmount').focus();
        $('input#realAmount').css('border-color', 'red');
        return ret;
    }
    toNormalBorder('realAmount');
    
    // Amount must be localized number
    var lcInt   =   locale(decimalPoint, thousandSep, 0);
    var val     =   parseLcNum(amount, lcInt);
    if ((!amount.match(/^[0-9, \,, \.]+$/) || isNaN(val) || val <= 0)) {   
        ret['result']   =   false;
        ret['msg']      =   _('Invalid amount');
        $('input#realAmount').focus();
        $('input#realAmount').css('border-color', 'red');
        return ret;
    }
    toNormalBorder('realAmount');
     
    return ret;
}

function submitCollecting(print) {
    var data    =   $('#paymentSubmitFrm').serialize();
    $.ajax ({   
        type:       "POST", 
        url:        "../InsurancePayment/submitCollectingAjax?set_ajax_view",
        async:      false,
        data:       data,
        dataType:   "json",
        beforeSend: function() {
            $('#ajaxLoader').show();
        },
        complete:   function() {
            $('#ajaxLoader').hide();
        },      
        success:    function(data) {
            if (data.error.code == 'OK') {
                 showMessage('insurancePaymentMsg', _('Saving succeed'), 'success');
                 setTimeout("clearText('insurancePaymentMsg')", 20000);
                 setDataToElements({itemList: 'serviceListDiv', paymentSummary: 'paymentSummaryDiv'}, data.result);
                 if (print) {                                                           
                     displayError('Print function need to be implemented');
                 }
            }
            else {
                displayError(data.error.mess);              
            }                                                                                  
        }
    });        
}

function calculateInsurance(ticketId) {
    $.ajax ({   
        type:       "POST", 
        url:        "../InsurancePayment/calculateInsurancePaymentAjax?set_ajax_view",
        async:      false,
        data:       "ticketId=" + ticketId,
        dataType:   "json",
        beforeSend: function() {
            $('#ajaxLoader').show();
        },
        complete:   function() {
            $('#ajaxLoader').hide();
        },      
        success:    function(data) {
            if (data.error.code == 'OK') {
                 setDataToElements({itemList: 'serviceListDiv', paymentSummary: 'paymentSummaryDiv'}, data.result);
            }
            else {
                displayError(data.error.mess);              
            }                                                                                  
        }
    });   
}

function viewInsurancePaymentDetails(ticketId, dialogId) {
    var dialog  =   !!dialogId;
    $.ajax({
        type: "GET",
        url:  "../InsurancePayment/ViewTicketPaymentAjax?set_ajax_view",
        data: "ticketId=" + ticketId,
        dataType: "json",
        beforeSend: function() {
            showAjaxLoader('ajaxLoader', 'dummy', true);
            if (dialog) {
                $('#' + dialogId).dialog('close');
            }
        },
        complete: function() {
            showAjaxLoader('ajaxLoader', 'dummy', false);
        },    
        success: function(data) {
            if (data.error.code == 'OK') {
            	var containers =   {
			        patientCode:    'patientCode',
			        patientName:    'personName',
			        birthDay:       'dobText',
			        ticketList:     'ticketLbx',
			        insuranceCode:  'insuranceNumberTxt',
			        insuranceUsage: 'insuranceUsageTxt',
			        correctRoute:    'correctRouteChk',
			        continous36Month: '36MonthChk',
			        mainContent:    'insurancePaymentContentDiv'
            	};
                setDataToElements(containers, data.result);
            }
            else {
                displayError(data.error.mess);
            }
        }      
    });
}